package com.jd.user.interceptor;

import com.jd.basic.jwt.JwtUtils;
import com.jd.basic.jwt.LoginData;
import com.jd.basic.jwt.Payload;
import com.jd.basic.jwt.RsaUtils;
import com.jd.system.annotation.PreAuthorize;
import com.jd.system.mapper.PermissionMapper;
import com.jd.user.domain.Logininfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.security.PublicKey;
import java.util.List;

@Component
public class LoginInterceptor implements HandlerInterceptor {

    @Autowired
    private RedisTemplate redisTemplate;
    @Autowired
    private PermissionMapper permissionMapper;
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        // 获取token请求头
        String token = request.getHeader("token");
        if (token != null){
            //解密
            Logininfo logininfo = null;
            try {
                // 获取公钥
                PublicKey publicKey = RsaUtils.getPublicKey(JwtUtils.class.getClassLoader().getResource("auth_rsa.pub").getFile());
                Payload<LoginData> payload = JwtUtils.getInfoFromToken(token, publicKey, LoginData.class);
                logininfo = payload.getLoginData().getLogininfo();
            } catch (Exception e) {
                response.setContentType("application/json;charset=UTF-8");
                response.getWriter().println(" {\"success\":false,\"msg\":\"timeout\"}");
                return false;
            }
            // 登录传给，验证权限
            if (logininfo.getType()==1){//1为前台用户，直接放行
                return true;
            }
            // 2.为后台管理员，先验证权限
            HandlerMethod method = (HandlerMethod)handler; //你访问的是哪一个接口就是哪一个接口方法
            //获取接口上名称为PreAuthorize的注解
            PreAuthorize preAuthorize = method.getMethodAnnotation(PreAuthorize.class);
            if(preAuthorize==null){//没有加注解不需要验证权限
                return true;
            }   //接口上有这个PreAuthorize注解 - 验证
                //获取sn属性值
                String sn = preAuthorize.sn();
                //获取当前登录人所有权限
                List<String> myPermissions = permissionMapper.getPermissionsByLogininfoId(logininfo.getId());
                //2. 获取当前登录人的所有权限的sn
                //3.判断：包含 - 有权限 - 放行。不包含 - 没有权限 - 返回没有权限的信息
                if(myPermissions.contains(sn)){
                    return true;
                }else{//没有权限去访问
                    response.setContentType("application/json;charset=UTF-8");
                    response.getWriter().println("{\"success\":false,\"msg\":\"noPermission\"}");
                    return false;
                }



        }
        //告诉浏览器我要给你返回一个json格式的数据，浏览器就会以json格式的数据进行转换
        response.setContentType("application/json;charset=UTF-8");
        response.getWriter().println("{\"success\":false,\"msg\":\"noLogin\"}");
        return false;
    }
}
